package io.vov.vitamio.listener;

import java.io.IOException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;

import com.naduolai.android.util.Log;

public class NetworkListener {
	//Log日志
	private static final String LOG_TAG = NetworkListener.class.getName();
	//网络已连接广播事件
	private static final String NETWORK_CONNECTION_ACTION = "com.naduolai.network.connection.action";
	//网络断开广播事件
	private static final String NETWORK_DISCONNECTION_ACTION = "com.naduolai.network.disconnection.action";
	//Context
	private Context mContext = null;
	//当前类对象
	private static NetworkListener mNetworkListener = null;
	//广播对象
	private NetworkStateReceiver mNetworkStateReceiver = null;
	public  NetworkListener(Context context) {
		mContext = context;
		//注册网络监听
		registerNetworkReceiver();
	}
	/**
	 * 获取当前类单例对象
	 * @param context 上下文对象
	 * @return
	 */
	public static NetworkListener getInstance(Context context) {
		if (mNetworkListener == null) {
			mNetworkListener = new NetworkListener(context);
		}
		return mNetworkListener;
	}
	/**
	 * 启动网络状态监听
	 */
	public void startNetworkListener() {
		//启动线程监听网络状态
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						//拼网络,判断网络是否连接到外网.
						boolean connectNetworkBool  = pingHost("baidu.com");
						Log.debug(LOG_TAG, "网络连接状态::->" + connectNetworkBool);
						if (connectNetworkBool) {
							//发生网络已连接广播
							Intent intent = new Intent(NetworkListener.NETWORK_CONNECTION_ACTION); 
			                mContext.sendBroadcast(intent);   
						} else {
							//发生网络断开连接广播
							Intent intent = new Intent(NetworkListener.NETWORK_DISCONNECTION_ACTION); 
			                mContext.sendBroadcast(intent); 
						}
						//休眠5秒
//						Thread.sleep(60 * 1000);
					} catch (Exception e) {
						Log.e(LOG_TAG, "", e);
					}
				}
			}
		}).start();
	}
	/**
	 * 注册网络状态监听器
	 */
	@SuppressWarnings("unused")
	private void registerNetworkReceiver() {
		//注册网络监听   
		//WifiManager.SCAN_RESULTS_AVAILABLE_ACTION和 WifiManager.WIFI_STATE_CHANGED_ACTION
		mNetworkStateReceiver = new NetworkStateReceiver();
		IntentFilter filter = new IntentFilter();    
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);   
		mContext.registerReceiver(mNetworkStateReceiver, filter); 
	}
	/**
	 * 监听网络状态变化广播
	 * @name NetworkListener.java 
	 * @author 亚明
	 * @Date 2013-3-21
	 * @Description
	 */
	class NetworkStateReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.e(LOG_TAG, "网络状态改变");   
			boolean success = false;   
			//获得网络连接服务   
			ConnectivityManager connManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);   
			// State state = connManager.getActiveNetworkInfo().getState();
			//获取Wi-Fi网络连接状态   
			State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState(); 
			//判断是否正在使用WIFI网络   
			if (State.CONNECTED == state) { 
				//网络为已连接状态
				success = true;  
				System.out.println("Wi-Fi网络连接");
				//Toast.makeText(mContext, "Wi-Fi网络连接", Toast.LENGTH_LONG).show();
			}   
			 //获取GPRS网络连接状态   
			state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
			//判断是否正在使用GPRS网络   
			if (State.CONNECTED == state) { 
				//网络为已连接状态
				success = true;   
				System.out.println("GPRS网络连接");
				//Toast.makeText(mContext, "GPRS网络连接", Toast.LENGTH_LONG).show();
			}   
			//获取以太网网络连接状态   
			state = connManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET).getState(); 
			//判断是否正在使用以太网网络   
			if (State.CONNECTED == state) { 
				//网络为已连接状态
				success = true;   
				System.out.println("以太网网络连接");
				//Toast.makeText(mContext, "以太网网络连接", Toast.LENGTH_LONG).show();
			}   
			if (!success) {  
				System.out.println("您的网络连接已中断");
				//Toast.makeText(mContext, "您的网络连接已中断", Toast.LENGTH_LONG).show();   
			} 
			System.out.println("连接状态:" + getAPNType());
			//Toast.makeText(mContext, "连接状态:" + getAPNType(), Toast.LENGTH_LONG).show(); 
		}
	} 
	/**
	 * ping接网络地址
	 * @param str
	 * @return
	 */
	public boolean pingHost(String str){
		//是否连接上网络(true:连接   false:未连接)
		boolean resaultBool = false;  
        try {  
            //Hardcoded for now, make it UI configurable   
            Process p = Runtime.getRuntime().exec("ping -c 1 -w 100 " +str);  
            int status = p.waitFor();  
            if (status == 0) {  
                //resault="success";
            	resaultBool = true;
            } else {  
                //resault="faild";
            	resaultBool = false;
            }  
        } catch (IOException e) {   
        	Log.e(LOG_TAG, "ping 网络发生异常..", e);
        } catch (InterruptedException e) {    
        	Log.e(LOG_TAG, "ping 网络发生异常..", e);
        }  
        return resaultBool;  
    }
	
	/**
	 * 获取当前的网络状态  -1:没有网络、1:WIFI网络、2:wap网络、3:net网络
	 * @return
	 */
	public int getAPNType(){ 
		int netType = -1;  
		ConnectivityManager connMgr = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
		if(networkInfo == null){ 
			return netType; 
		} 
		int nType = networkInfo.getType(); 
		if(nType == ConnectivityManager.TYPE_MOBILE){ 
			Log.e("networkInfo.getExtraInfo()", "networkInfo.getExtraInfo() is "+networkInfo.getExtraInfo()); 
			if(networkInfo.getExtraInfo().toLowerCase().equals("cmnet")){ 
				netType = /*CMNET*/2;
			} else{ 
				netType = /*CMWAP*/3;
			} 
		} else if(nType==ConnectivityManager.TYPE_WIFI){ 
			netType = /*WIFI*/1; 
		} 
		return netType; 
	} 
	
	/**
	 * 注销网络监听
	 */
	public void onDestroy() {
		//在Activity中的onDestroy中注销网络监听   java.lang.IllegalArgumentException: Receiver not registered
		if (mNetworkStateReceiver != null) {
			mContext.unregisterReceiver(mNetworkStateReceiver);
		}
	}
}
